package cn.walls1717.juc.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 等待与唤醒测试
 *
 * @author walls1717
 * @create 2022/12/10 15:45
 **/
@Slf4j
public class LockSupportDemo {

    public static void main(String[] args) throws InterruptedException {
        // m1();
        // m2();
        Thread t1 = new Thread(() -> {
            log.info("t1 come in ...");
            LockSupport.park();
            log.info("t1 up ...");
        }, "t1");
        t1.start();

        new Thread(()->{
            log.info("t2发出唤醒通知");
            LockSupport.unpark(t1);
        }, "t2").start();
    }

    /**
     * 使用ReentrantLock的condition中await与signal实现等待与唤醒
     *
     * @throws InterruptedException .
     */
    private static void m2() throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        new Thread(()->{
            lock.lock();
            try {
                log.info("t1 come in ...");
                condition.await();
                log.info("t1 up ...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t1").start();

        TimeUnit.SECONDS.sleep(1);

        new Thread(()->{
            lock.lock();
            try {
                log.info("t2 发出唤醒通知");
                condition.signal();
            } finally {
                lock.unlock();
            }
        }, "t2").start();
    }

    /**
     * 使用wait与notify组合实现等待唤醒
     */
    private static void m1() {
        Object o = new Object();

        new Thread(()->{
            synchronized (o) {
                log.info("t1 come in ...");

                try {
                    o.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                log.info("t1 up...");
            }
        }, "t1").start();

        new Thread(()->{
            synchronized (o) {
                log.info("t2发出唤醒通知");
                o.notify();
            }
        }, "t2").start();
    }
}
